<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />

			<cl-filter label="类型">
				<cl-select :options="options.types" prop="type" :width="150" />
			</cl-filter>

			<cl-filter label="显示状态">
				<cl-select :options="options.visibility" prop="isVisible" :width="120" />
			</cl-filter>

			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key placeholder="搜索标题" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<template #column-style="{ scope }">
					<el-tooltip effect="dark" placement="top">
						<template #content>
							<div class="whitespace-pre">
								{{ JSON.stringify(scope.row.style, null, 2) }}
							</div>
						</template>
						<el-tag size="small" type="info">查看样式</el-tag>
					</el-tooltip>
				</template>

				<!-- 自定义排序操作按钮 -->
				<template #column-orderOp="{ scope }">
					<div class="flex items-center space-x-1">
						<el-tooltip content="上移" placement="top">
							<el-button
								:disabled="isFirst(scope.row)"
								link
								@click="moveOrder(scope.row, 'up')"
							>
								<el-icon><arrow-up /></el-icon>
							</el-button>
						</el-tooltip>
						<el-tooltip content="下移" placement="top">
							<el-button
								:disabled="isLast(scope.row)"
								link
								@click="moveOrder(scope.row, 'down')"
							>
								<el-icon><arrow-down /></el-icon>
							</el-button>
						</el-tooltip>
					</div>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>

<script lang="ts" name="app-goods" setup>
import { useCrud, useTable, useUpsert } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue';

const { service } = useCool();

// 定义布局配置接口
interface LayoutConfig {
	id: string;
	type: string;
	title: string;
	showTitle: boolean;
	isVisible: boolean;
	order: number;
	categoryId?: number;
	gridCols?: number;
	style: {
		container: string;
		title?: string;
	};
}

const options = reactive({
	types: [
		{ label: '横幅', value: 'banner' },
		{ label: '限时特卖', value: 'flash-sale' },
		{ label: '商品展示', value: 'product-showcase' },
		{ label: '商品网格', value: 'product-grid' },
		{ label: '商品轮播', value: 'product-carousel' },
		{ label: '品牌展示', value: 'brands' },
		{ label: '新品上市', value: 'new-arrivals' },
		{ label: '健康资讯', value: 'topics' },
		{ label: '用户评价', value: 'reviews' },
		{ label: '用户活动', value: 'user-activity' }
	],
	visibility: [
		{ label: '显示', value: true },
		{ label: '隐藏', value: false }
	]
});

// 表格数据
const tableData = ref<LayoutConfig[]>([]);

// 判断是否为第一行
function isFirst(row: LayoutConfig) {
	const list = Table.value?.data || [];
	return list[0]?.id === row.id;
}

// 判断是否为最后一行
function isLast(row: LayoutConfig) {
	const list = Table.value?.data || [];
	return list[list.length - 1]?.id === row.id;
}

// 移动排序
async function moveOrder(row: LayoutConfig, type: 'up' | 'down') {
	const list = Table.value?.data || [];
	const index = list.findIndex(item => item.id === row.id);

	if (index === -1) return;

	const targetIndex = type === 'up' ? index - 1 : index + 1;
	if (targetIndex < 0 || targetIndex >= list.length) return;

	// 交换order值
	const targetRow = list[targetIndex];
	const tempOrder = row.order;
	row.order = targetRow.order;
	targetRow.order = tempOrder;

	try {
		// 更新两行的顺序
		await Promise.all([
			service.app.layout.update({
				id: row.id,
				order: row.order
			}),
			service.app.layout.update({
				id: targetRow.id,
				order: targetRow.order
			})
		]);

		ElMessage.success('排序更新成功');
		// 刷新列表
		Crud.value?.refresh();
	} catch (e) {
		ElMessage.error('排序更新失败');
		console.error(e);
	}
}

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			prop: 'id',
			label: '模块ID',
			required: true,
			component: {
				name: 'el-input',
				props: {
					placeholder: '请输入唯一的模块ID'
				}
			}
		},
		{
			prop: 'type',
			label: '模块类型',
			required: true,
			component: {
				name: 'el-select',
				options: options.types
			}
		},
		{
			prop: 'title',
			label: '标题',
			component: {
				name: 'el-input',
				props: {
					placeholder: '请输入模块标题'
				}
			}
		},
		{
			prop: 'showTitle',
			label: '显示标题',
			value: true,
			component: { name: 'cl-switch' }
		},
		{
			prop: 'isVisible',
			label: '是否显示',
			value: true,
			component: { name: 'cl-switch' }
		},
		{
			prop: 'order',
			label: '排序',
			required: true,
			hook: { bind: ['number'] },
			component: {
				name: 'el-input-number',
				props: {
					min: 1,
					placeholder: '数字越小越靠前'
				}
			}
		},
		{
			prop: 'categoryId',
			label: '分类ID',
			hook: { bind: ['number'] },
			component: {
				name: 'el-input-number',
				props: { min: 1 }
			},
			hidden: ({ scope }) => {
				return !['product-showcase', 'product-grid', 'product-carousel'].includes(
					scope.type
				);
			}
		},
		{
			prop: 'gridCols',
			label: '网格列数',
			hook: { bind: ['number'] },
			component: {
				name: 'el-input-number',
				props: {
					min: 1,
					max: 6
				}
			},
			hidden: ({ scope }) => scope.type !== 'product-grid'
		},
		{
			prop: 'style',
			label: '样式配置',
			component: {
				name: 'el-input',
				props: {
					type: 'textarea',
					rows: 6,
					placeholder: '请输入JSON格式的样式配置'
				}
			},
			hook: {
				bind(value) {
					return typeof value === 'object' ? JSON.stringify(value, null, 2) : value;
				},
				submit(value, { form, prop }) {
					try {
						form[prop] = value ? JSON.parse(value) : {};
					} catch (e) {
						console.error('JSON parse error:', e);
						form[prop] = {};
					}
				}
			}
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection' },
		{ prop: 'id', label: '模块ID', minWidth: 120 },
		{ prop: 'type', label: '类型', dict: options.types, minWidth: 120 },
		{ prop: 'title', label: '标题', minWidth: 150 },
		{ prop: 'showTitle', label: '显示标题', component: { name: 'cl-switch' }, minWidth: 80 },
		{ prop: 'isVisible', label: '是否显示', component: { name: 'cl-switch' }, minWidth: 80 },
		{ prop: 'order', label: '排序', sortable: 'custom', minWidth: 80 },
		{ prop: 'categoryId', label: '分类ID', minWidth: 80 },
		{ prop: 'gridCols', label: '网格列数', minWidth: 80 },
		{ prop: 'style', label: '样式配置', minWidth: 100 },
		{ prop: 'createTime', label: '创建时间', sortable: 'desc', minWidth: 160 },
		{ prop: 'updateTime', label: '更新时间', sortable: 'custom', minWidth: 160 },
		{
			prop: 'orderOp',
			label: '排序操作',
			width: 100
		},
		{
			type: 'op',
			buttons: ['edit', 'delete'],
			width: 160
		}
	]
});

// cl-crud
const Crud = useCrud(
	{
		service: service.app.layout
	},
	app => {
		app.refresh();
	}
);

// 监听表格数据变化
Table.value?.onLoad(({ list }) => {
	tableData.value = list as unknown as LayoutConfig[];
});
</script>

<style lang="scss" scoped>
.whitespace-pre {
	white-space: pre;
}

.flex {
	display: flex;
}

.items-center {
	align-items: center;
}

.space-x-1 > * + * {
	margin-left: 0.25rem;
}
</style>
